package com.flowerplus.store.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.design.widget.TabLayout;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flowerplus.store.App;
import com.flowerplus.store.constant.Constant;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

/**
 * Created by dongliangshi on 2016/11/10.
 */

public class Utils {
    private Utils(){}
    //签名算法
    public static String getSign(HashMap<String,String> map) {
        ArrayList<String> allKey = new ArrayList<>();

        for(String key : map.keySet()) {
            allKey.add(key);
        }

        Collections.sort(allKey);

        StringBuffer sb = new StringBuffer("");
        for (String key : allKey) {
            if (!Constant.SIGN.equals(key)&&!TextUtils.isEmpty(map.get(key))) {
                sb.append(key).append("=").append(map.get(key)).append("&");
            }
        }
        return MD5(sb.toString()).toLowerCase();
    }

    public static String MD5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes());
            byte[] digest = md5.digest();
            return byte2String(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String byte2String(byte[] b){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < b.length; i ++){
            int a = b[i];
            if(a<0)
                a+=256;
            if(a<16)
                sb.append("0");
            sb.append(Integer.toHexString(a));

        }
        return sb.toString();
    }

    public static String getVersionName() {
        PackageManager pm = App.getApp().getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(App.getApp().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return pi.versionName;
    }

    //拿到屏幕宽度
    public static int getWinWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int getWinHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static int px2dp(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px/scale + 0.5);
    }

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) ((dp - 0.5)*scale);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }








    //string
    public static String getString(int stringId) {
        return App.getApp().getString(stringId);
    }

    //color
    public static int getColor(int colorId) {
        int color = App.getApp().getResources().getColor(colorId);
        return color;
    }


    // IMEI码
    private static String getIMIEStatus(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        return deviceId;
    }

    // Mac地址
    public static String getLocalMac(Context context) {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /*
    * 获取到客户ID，即IMSI(用于识别移动用户所归属的移动通信网；MSIN是移动用户识别码，用以识别某一移动通信网中的移动用户)
    *
            * @return
            */
    public static String getIMSI(Context mContext) {
        TelephonyManager telephonyManager = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getSubscriberId();
    }

    /**
     * 获取设备id  获取手机的IMEI号码(是移动设备国际身份码的缩写，移动设备国际辨识码，是由15位数字组成的"电子串号"，它与每台手机一一对应，
     * 而且该码是全世界唯一的)
     *
     * @return
     */
    public static String getIMEI(Context mContext) {
        String imei = "";

        TelephonyManager telephonyManager = (TelephonyManager) mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        imei = telephonyManager.getDeviceId();
        return imei;
    }
    public static int dip2px1(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static void reflex(final TabLayout tabLayout){
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dp10 = Utils.dip2px1(tabLayout.getContext(), 10);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width ;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 获取Application下面的metaData
     *
     * @return
     * @author SHANHY
     * @date   2015年12月30日
     */
    public static String getAppMetaData(String meta_name, Context context){
        try {
            ApplicationInfo appInfo =context.getPackageManager()
                    .getApplicationInfo(App.getApp().getPackageName(), PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(meta_name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
